<?php

declare(strict_types=1);

namespace App\Command;

use AdminBundle\Repositories\SystemMenuRepository;
use AdminBundle\Repositories\SystemPermissionsRepository;
use AdminBundle\Repositories\SystemRolesUserRepository;
use AdminBundle\Services\AdminService;
use AdminBundle\Services\RolesService;
use Hyperf\Command\Command as HyperfCommand;
use Hyperf\Command\Annotation\Command;
use Psr\Container\ContainerInterface;

/**
 * @Command
 */
#[Command]
class InitCommand extends HyperfCommand
{
    /**
     * @var ContainerInterface
     */
    protected $container;

    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;

        parent::__construct('init');
    }

    public function configure()
    {
        parent::configure();
        $this->setDescription('项目初始化');
    }

    public function handle()
    {
        $this->init();
        $this->line('初始化完成', 'info');
    }

    protected function init()
    {
        $file = __DIR__ . '/../../install.lock';
        if (file_exists($file)) {
            $this->line('已初始化完成', 'info');
            return true;
        }
        $lock = fopen($file, "w") or die("Unable to open file!");
        fwrite($lock, '已执行初始化');

        $this->line('正在执行数据库迁移', 'info');
        $this->call('migrate');
        
        $adminService = new AdminService();
        $adminService->register([
            'username' => '超级管理员',
            'account' => 'admin',
            'avatar' => 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif',
            'password' => password_hash('123456', PASSWORD_DEFAULT),
        ]);

        $adminService->register([
            'username' => 'test',
            'account' => 'test',
            'password' => password_hash('123456', PASSWORD_DEFAULT),
        ]);

        //创建超级管理员角色
        $rolesService = new RolesService();
        $rolesService->saveRolesPermissions([
            'description' => "系统内置",
            'display_name' => "超级管理员",
            'name' => "administrator"
        ]);

        //为超级管理员赋予角色
        SystemRolesUserRepository::instance()->saveData([
            'system_role_id' => 1,
            'user_id' => 1,
        ]);

        $file = file_get_contents(__DIR__ . '/../../migrations/db.json');
        $fileArr = json_decode($file, true);
        SystemMenuRepository::instance()->saveManyData($fileArr['menu']);
        SystemPermissionsRepository::instance()->saveManyData($fileArr['permissions']);

        return true;
    }
}
